package io.example.jdbc;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2018/3/9.
 * 数据初始化
 */
public class DataInitVerticle extends AbstractVerticle {

    private static Logger logger = LoggerFactory.getLogger(DataInitVerticle.class);


    @Override
    public void start(Future<Void> startFuture) throws Exception {
        final JDBCClient client = JDBCClient.createShared(vertx, config());

        client.getConnection(conn -> {
            if (conn.failed()) {
                dataInitError(startFuture, conn.cause());
                return;
            }
            final SQLConnection connection = conn.result();
            String createTableSql = "create table if not exists test(id integer identity primary key, name varchar(255) unique)";
            logger.debug("execute sql: {}", createTableSql);
            connection.execute(createTableSql, create -> {
                if (create.failed()) {
                    dataInitError(startFuture, create.cause());
                    return;
                }
                String initDataSql = "insert into test (name) values ('Hello'), ('World')";
                logger.debug("execute sql: {}", initDataSql);
                connection.execute(initDataSql, insert -> {
                    // query some data with arguments
                    if (insert.failed()) {
                        dataInitError(startFuture, insert.cause());
                    }
                    //and close the connection
                    connection.close(done -> {
                        if (done.failed()) {
                            dataInitError(startFuture, done.cause());
                        } else {
                            startFuture.complete();
                        }
                    });
                });
            });
        });
    }

    private void dataInitError(Future<Void> startFuture, Throwable cause) {
        logger.error("Database init error", cause);
        startFuture.fail(cause);
    }
}
